package cn.sciento.websocket.redis;

import cn.sciento.core.convertor.ApplicationContextHelper;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import cn.sciento.core.redis.RedisHelper;
import cn.sciento.websocket.config.WebSocketConfig;
import org.springframework.context.ApplicationContext;

public class BrokerRedis {
    private static RedisHelper redisHelper;

    private static RedisHelper getRedisHelper() {
        ApplicationContext applicationContext = ApplicationContextHelper.getContext();
        if (redisHelper == null) {
            redisHelper = applicationContext.getBean(RedisHelper.class);
        }
        redisHelper.setCurrentDatabase(applicationContext.getBean(WebSocketConfig.class).getRedisDb());
        return redisHelper;
    }

    private static void clear() {
        if (redisHelper == null) {
            redisHelper = ApplicationContextHelper.getContext().getBean(RedisHelper.class);
        }
        redisHelper.clearCurrentDatabase();
    }

    private static String getCacheKey(String brokerId) {
        return "websocket:brokers:" + brokerId;
    }

    public static void refreshCache(String brokerId) {
        clearRedisCache(getRedisHelper(), brokerId);
        getRedisHelper().strSet(getCacheKey(brokerId), "$", 15L, TimeUnit.SECONDS);
        clear();
    }

    public static boolean isAlive(String brokerId) {
        String result = getRedisHelper().strGet(getCacheKey(brokerId));
        clear();
        return Objects.equals(result, "$");
    }

    private static void clearRedisCache(RedisHelper redisHelper, String brokerId) {
        redisHelper.delKey(getCacheKey(brokerId));
        clear();
    }
}
